<template>
  <div class="artwork-list">
    <!-- 图片预览组件 -->
    <image-preview 
      :visible="showImagePreview" 
      :image-url="previewImageUrl" 
      :alt-text="previewImageAlt"
      @close="closeImagePreview"
    />
    <a-page-header
      title="作品管理"
      sub-title="管理系统中的作品，包括新增、编辑、删除和审核等操作。"
    />
    <a-divider />
    <a-card class="search-card">
      <template #title>
        <span>搜索条件</span>
        <a-divider type="vertical" />
      </template>
      <a-form layout="inline">
        <a-form-item label="作品名称">
          <a-input v-model:value="searchForm.title" placeholder="请输入作品名称" allowClear />
        </a-form-item>
        <a-form-item label="作品分类">
          <a-select
            v-model:value="searchForm.categoryId"
            placeholder="请选择作品分类"
            allowClear
            style="width: 200px"
          >
            <a-select-option v-for="item in categoryList" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="审核状态">
          <a-select
            v-model:value="searchForm.status"
            placeholder="请选择审核状态"
            allowClear
            style="width: 150px"
          >
            <a-select-option :value="0">草稿</a-select-option>
            <a-select-option :value="1">审核中</a-select-option>
            <a-select-option :value="2">已发布</a-select-option>
            <a-select-option :value="3">已拒绝</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><search-outlined /></template>查询
            </a-button>
            <a-button @click="resetSearch">
              <template #icon><reload-outlined /></template>重置
            </a-button>
            <!-- 暂时禁用新增按钮 -->
            <!-- <a-button type="primary" @click="showAddModal" v-permission="'content:artwork:add'">
              <template #icon><plus-outlined /></template>新增作品
            </a-button> -->
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <a-table 
        bordered
        :columns="columns" 
        :data-source="artworkList" 
        :loading="tableLoading" 
        :pagination="{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`
        }"
        @change="handleTableChange"
        rowKey="id">
        <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
            <a-space>
                <a-button type="primary" @click="showEditModal(record)" v-permission="'content:artwork:edit'">
                  <template #icon><edit-outlined /></template>编辑
                </a-button>
                <a-button type="primary" @click="showReviewModal(record)" v-permission="'content:artwork:review'">
                  <template #icon><check-outlined /></template>审核
                </a-button>
                <a-popconfirm
                title="确定要删除这个作品吗？"
                @confirm="handleDelete(record.id)"
                ok-text="确定"
                cancel-text="取消"
                >
                <a-button type="primary" danger v-permission="'content:artwork:delete'">
                  <template #icon><delete-outlined /></template>删除
                </a-button>
                </a-popconfirm>
            </a-space>
            </template>
            <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
            </a-tag>
            </template>
            <template v-else-if="column.key === 'cover'">
              <img v-if="record.coverImage" :src="`/api${record.coverImage}`" alt="封面" style="width: 80px; height: 80px; object-fit: cover; border-radius: 4px;" />
              <span v-else>-</span>
            </template>
        </template>
    </a-table>

    <!-- 新增/编辑作品弹窗 -->
    <a-modal
      :title="modalTitle"
      :visible="modalVisible"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :confirmLoading="modalLoading"
      width="700px"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="作品名称" name="title">
          <a-input v-model:value="formState.title" placeholder="请输入作品名称" />
        </a-form-item>
        <a-form-item label="作品分类" name="categoryId">
          <a-select
            v-model:value="formState.categoryId"
            placeholder="请选择作品分类"
            style="width: 100%"
          >
            <a-select-option v-for="item in categoryList" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="作品封面" name="coverImage">
          <a-upload
            v-model:file-list="fileList"
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            action="/api/upload"
            :before-upload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="imageUrl" :src="imageUrl.startsWith('data:') ? imageUrl : `/api${imageUrl}`" alt="cover" style="width: 100%; height: 100%; border-radius: 8px; object-fit: cover" />
            <div v-else>
              <loading-outlined v-if="imageLoading"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        
        <a-form-item label="作品图片" name="images">
          <div class="artwork-images-container">
            <!-- 已上传图片预览 -->
            <div class="artwork-images-preview" v-if="artworkImages.length > 0">
              <div v-for="(image, index) in artworkImages" :key="index" class="image-item">
                <img :src="`/api${image.imagePath}`" alt="作品图片" @click="previewImage(`/api${image.imagePath}`)" />
                <div class="image-actions">
                  <a-button type="primary" danger size="small" @click="removeImage(index)">
                    <template #icon><delete-outlined /></template>
                  </a-button>
                </div>
              </div>
            </div>
            
            <!-- 上传新图片 -->
            <a-upload
              name="file"
              list-type="picture-card"
              :show-upload-list="false"
              action="/api/upload"
              :before-upload="beforeUploadImage"
              @change="handleImageChange"
            >
              <div>
                <plus-outlined />
                <div style="margin-top: 8px">添加图片</div>
              </div>
            </a-upload>
          </div>
        </a-form-item>
        <a-form-item label="作品简介" name="description">
          <a-textarea v-model:value="formState.description" placeholder="请输入作品简介" :rows="4" />
        </a-form-item>
        <a-form-item label="作品标签" name="tags">
          <a-select
            v-model:value="formState.tags"
            mode="tags"
            placeholder="输入标签名称后按回车添加"
            style="width: 100%"
            :options="[]"
            :tokenSeparators="[',']"
          >
          </a-select>
          <!-- <div class="tag-tips">最多添加5个标签，输入后按回车或逗号添加</div> -->
        </a-form-item>
        <a-form-item label="参加活动" name="isActivity">
          <a-radio-group v-model:value="formState.isActivity">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="0">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="活动ID" name="activityId" v-if="formState.isActivity === 1">
          <a-input-group compact>
            <a-input-number 
              v-model:value="formState.activityId" 
              :min="1" 
              style="width: calc(100% - 90px)" 
              placeholder="请选择活动ID" 
              readonly 
              disabled
            />
            <a-button type="primary" @click="showActivityModal" style="width: 90px">选择活动</a-button>
          </a-input-group>
          <div class="activity-tip" v-if="formState.activityName">
            <span>已选择：{{ formState.activityName }}</span>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 审核作品弹窗 -->
    <a-modal
      title="审核作品"
      :visible="reviewModalVisible"
      @ok="handleReviewModalOk"
      @cancel="handleReviewModalCancel"
      :confirmLoading="reviewModalLoading"
      width="800px"
    >
      <div class="artwork-detail">
        <h3>{{ artworkDetail.title }}</h3>
        <p class="description">{{ artworkDetail.description || '暂无描述' }}</p>
        <p><strong>分类：</strong>{{ artworkDetail.categoryName }}</p>
        <!-- 图片轮播 -->
        <div class="artwork-images" v-if="artworkDetail.images && artworkDetail.images.length > 0">
          <a-carousel 
            v-model:current="currentImageIndex"
            @change="setImage"
            arrows
            class="carousel-container"
          >
            <template #prevArrow>
              <div class="custom-slick-arrow" style="left: 10px; z-index: 1">
                <left-circle-outlined />
              </div>
            </template>
            <template #nextArrow>
              <div class="custom-slick-arrow" style="right: 10px">
                <right-circle-outlined />
              </div>
            </template>
            <div v-for="image in artworkDetail.images" :key="image.id" class="carousel-slide">
              <img :src="`/api${image.imagePath}`" alt="作品图片" class="carousel-image" @click="previewImage(`/api${image.imagePath}`)" />
            </div>
          </a-carousel>
        </div>
      </div>

      <a-divider />
      
      <a-form
        ref="reviewFormRef"
        :model="reviewFormState"
        :rules="reviewRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="审核结果" name="status">
          <a-radio-group v-model:value="reviewFormState.status">
            <a-radio :value="2">通过</a-radio>
            <a-radio :value="3">拒绝</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="拒绝原因" name="rejectReason" v-if="reviewFormState.status === 3">
          <a-textarea v-model:value="reviewFormState.rejectReason" placeholder="请输入拒绝原因" :rows="4" />
        </a-form-item>
      </a-form>
    </a-modal>
    
    <!-- 活动选择弹窗 -->
    <a-modal
      title="选择活动"
      :visible="activityModalVisible"
      @cancel="handleActivityModalCancel"
      :footer="null"
      width="800px"
    >
      <div class="activity-selector">
        <div class="search-bar">
          <a-input
            v-model:value="activitySearchKeyword"
            placeholder="请输入活动名称"
            style="width: 250px; margin-right: 8px"
            @pressEnter="searchActivities"
          />
          <a-button type="primary" @click="searchActivities">
            <template #icon><search-outlined /></template>搜索
          </a-button>
        </div>
        
        <a-table
          :columns="activityColumns"
          :data-source="activityList"
          :loading="activityLoading"
          :pagination="activityPagination"
          @change="handleActivityTableChange"
          rowKey="id"
          bordered
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'cover'">
              <img v-if="record.coverImage" :src="`/api${record.coverImage}`" alt="活动封面" style="width: 60px; height: 30px; object-fit: cover; border-radius: 4px;" />
              <span v-else>-</span>
            </template>
            <template v-else-if="column.key === 'status'">
              <a-tag :color="getActivityStatusColor(record.status)">
                {{ getActivityStatusText(record.status) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'action'">
              <a-button type="primary" size="small" @click="selectActivity(record)">
                选择
              </a-button>
            </template>
          </template>
        </a-table>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from 'vue';
import { message, PageHeader } from 'ant-design-vue';
import {   LeftCircleOutlined, RightCircleOutlined, SearchOutlined, ReloadOutlined, PlusOutlined, EditOutlined, DeleteOutlined, CheckOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import axios from 'axios';
import ImagePreview from '@/components/ImagePreview.vue';

export default defineComponent({
  name: 'ArtworkList',
  components: {
    SearchOutlined,
    ReloadOutlined,
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    CheckOutlined,
    LoadingOutlined,
    LeftCircleOutlined,
    RightCircleOutlined,
    APageHeader: PageHeader,
    ImagePreview
  },
  setup() {
    const tableLoading = ref(false);
    const artworkList = ref([]);
    const categoryList = ref([]);
    const imageUrl = ref('');
    const imageLoading = ref(false);
    const fileList = ref([]);
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
    });

    const searchForm = reactive({
      title: '',
      categoryId: undefined,
      status: undefined,
    });
    
    const getBase64 = (img, callback) => {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result));
      reader.readAsDataURL(img);
    };

    const beforeUpload = (file) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('只能上传 JPG/PNG 格式的图片！');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片大小不能超过 2MB！');
      }
      return isJpgOrPng && isLt2M;
    };

    const handleChange = (info) => {
      if (info.file.status === 'uploading') {
        imageLoading.value = true;
        return;
      }
      if (info.file.status === 'done') {
        // 获取服务器返回的图片URL
        if (info.file.response.code === 200) {
          formState.coverImage = info.file.response.data;
          getBase64(info.file.originFileObj, (base64Url) => {
            imageUrl.value = base64Url;
            imageLoading.value = false;
          });
        } else {
          message.error('上传失败');
          imageLoading.value = false;
        }
      }
      if (info.file.status === 'error') {
        imageLoading.value = false;
        message.error('上传失败');
      }
    };

    const columns = [
      {
        title: '序号',
        key: 'index',
        width: 80,
        customRender: ({ index }) => index + 1
      },
      {
        title: '作品名称',
        dataIndex: 'title',
        key: 'title',
        customRender: ({ text }) => text || '-'
      },
      {
        title: '封面',
        dataIndex: 'coverImage',
        key: 'cover',
      },
      {
        title: '分类',
        dataIndex: 'categoryName',
        key: 'categoryName',
        customRender: ({ text }) => text || '-'
      },
      {
        title: '参加活动',
        key: 'isActivity',
        width: 100,
        customRender: ({ record }) => {
          return record.isActivity === 1 ? '是' : '否';
        }
      },
      {
        title: '活动名称',
        dataIndex: 'activityName',
        key: 'activityName',
        customRender: ({ text }) => {
          return text || '-';
        }
      },
      {
        title: '浏览量',
        dataIndex: 'viewCount',
        key: 'viewCount',
        customRender: ({ text }) => text || '0'
      },
      {
        title: '收藏数',
        dataIndex: 'favoriteCount',
        key: 'favoriteCount',
        customRender: ({ text }) => text || '0'
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        customRender: ({ text }) => text || '-'
      },
      {
        title: '操作',
        key: 'action',
        width: 250,
      }
    ];

    // 获取作品列表
    const fetchArtworkList = (page = pagination.current, pageSize = pagination.pageSize) => {
      tableLoading.value = true;
      const params = {
        current: page,
        size: pageSize,
        ...searchForm
      };
      axios.get('/api/artwork/page', { params })
        .then(response => {
          if (response.data.code === 200) {
            artworkList.value = response.data.data.records;
            pagination.total = response.data.data.total;
            pagination.current = page;
            pagination.pageSize = pageSize;
          } else {
            message.error(response.data.message || '获取作品列表失败');
          }
        })
        .catch(error => {
          console.error('获取作品列表失败:', error);
          message.error('获取作品列表失败');
        })
        .finally(() => {
          tableLoading.value = false;
        });
    };

    // 获取分类列表
    const fetchCategoryList = () => {
      axios.get('/api/category/list')
        .then(response => {
          if (response.data.code === 200) {
            categoryList.value = response.data.data;
          } else {
            message.error(response.data.message || '获取分类列表失败');
          }
        })
        .catch(error => {
          console.error('获取分类列表失败:', error);
          message.error('获取分类列表失败');
        });
    };

    // 表格变化事件
    const handleTableChange = (pag) => {
      fetchArtworkList(pag.current, pag.pageSize);
    };

    // 搜索按钮点击事件
    const handleSearch = () => {
      // 搜索时重置到第一页
      fetchArtworkList(1, pagination.pageSize);
    };
    
    // 重置搜索条件
    const resetSearch = () => {
      searchForm.title = '';
      searchForm.categoryId = undefined;
      searchForm.status = undefined;
      fetchArtworkList(1, pagination.pageSize);
    };

    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 0: return '草稿';
        case 1: return '审核中';
        case 2: return '已发布';
        case 3: return '已拒绝';
        default: return '未知';
      }
    };

    // 获取状态颜色
    const getStatusColor = (status) => {
      switch (status) {
        case 0: return 'default';
        case 1: return 'orange';
        case 2: return 'green';
        case 3: return 'red';
        default: return 'default';
      }
    };

    // 新增/编辑弹窗相关
    const modalVisible = ref(false);
    const modalTitle = ref('新增作品');
    const modalLoading = ref(false);
    const isEdit = ref(false);
    const formRef = ref(null);
    const formState = reactive({
      id: null,
      title: '',
      categoryId: undefined,
      coverImage: '',
      description: '',
      tags: [],
      isActivity: 0,
      activityId: null,
      activityName: '',
    });
    
    // 活动选择相关
    const activityModalVisible = ref(false);
    const activityList = ref([]);
    const activityLoading = ref(false);
    const activitySearchKeyword = ref('');
    const activityPagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
    });
    
    const activityColumns = [
      {
        title: '序号',
        key: 'index',
        width: 80,
        customRender: ({ index }) => index + 1
      },
      {
        title: '封面',
        dataIndex: 'coverImage',
        key: 'cover',
        width: 80,
      },
      {
        title: '活动名称',
        dataIndex: 'name',
        key: 'name',
        ellipsis: true,
      },
      {
        title: '状态',
        key: 'status',
        width: 100,
      },
      {
        title: '时间',
        key: 'time',
        width: 240,
        customRender: ({ record }) => `${record.startTime || '-'} 至 ${record.endTime || '-'}`
      },
      {
        title: '操作',
        key: 'action',
        width: 100,
        fixed: 'right',
      }
    ];
    
    // 获取活动列表
    const fetchActivityList = async (page = 1, pageSize = 10) => {
      try {
        activityLoading.value = true;
        const params = {
          current: page,
          size: pageSize,
          name: activitySearchKeyword.value
        };
        const response = await axios.get('/api/activity/page', { params });
        if (response.data.code === 200) {
          activityList.value = response.data.data.records;
          activityPagination.total = response.data.data.total;
          activityPagination.current = page;
          activityPagination.pageSize = pageSize;
        } else {
          message.error(response.data.message || '获取活动列表失败');
        }
      } catch (error) {
        console.error('获取活动列表失败:', error);
        message.error('获取活动列表失败');
      } finally {
        activityLoading.value = false;
      }
    };
    
    // 活动表格变化事件
    const handleActivityTableChange = (pagination) => {
      fetchActivityList(pagination.current, pagination.pageSize);
    };
    
    // 搜索活动
    const searchActivities = () => {
      fetchActivityList(1, activityPagination.pageSize);
    };
    
    // 显示活动选择弹窗
    const showActivityModal = () => {
      activityModalVisible.value = true;
      activitySearchKeyword.value = '';
      fetchActivityList();
    };
    
    // 关闭活动选择弹窗
    const handleActivityModalCancel = () => {
      activityModalVisible.value = false;
      formState.activityId = null;
      formState.activityName = '';
    };
    
    // 选择活动
    const selectActivity = (record) => {
      formState.activityId = record.id;
      formState.activityName = record.name;
      activityModalVisible.value = false;
    };
    
    // 获取活动状态文本
    const getActivityStatusText = (status) => {
      switch (status) {
        case 0: return '投稿期';
        case 1: return '公示期';
        case 2: return '投票期';
        default: return '未知';
      }
    };
    
    // 获取活动状态颜色
    const getActivityStatusColor = (status) => {
      switch (status) {
        case 0: return 'green';
        case 1: return 'blue';
        case 2: return 'purple';
        default: return 'default';
      }
    };

    const rules = {
      title: [
        { required: true, message: '请输入作品名称', trigger: 'blur' },
        { max: 50, message: '作品名称不能超过50个字符', trigger: 'blur' }
      ],
      categoryId: [
        { required: true, message: '请选择作品分类', trigger: 'change' }
      ],
      coverImage: [
        { required: true, message: '请上传作品封面', trigger: 'change' }
      ],
      description: [
        { max: 1000, message: '作品简介不能超过1000个字符', trigger: 'blur' }
      ],
      activityId: [
        { required: true, message: '请选择活动', trigger: 'change', validator: (rule, value) => {
          if (formState.isActivity === 1 && !value) {
            return Promise.reject('请选择活动');
          }
          return Promise.resolve();
        }}
      ]
    };

    // 显示新增弹窗
    const showAddModal = () => {
      modalTitle.value = '新增作品';
      isEdit.value = false;
      formState.id = null;
      formState.title = '';
      formState.categoryId = undefined;
      formState.coverImage = '';
      formState.description = '';
      imageUrl.value = '';
      modalVisible.value = true;
    };

    // 显示编辑弹窗
    const showEditModal = async (record) => {
      modalTitle.value = '编辑作品';
      isEdit.value = true;
      
      try {
        // 获取作品详情，包括标签和图片
        const response = await axios.get(`/api/artwork/${record.id}`);
        if (response.data.code === 200) {
          const detailData = response.data.data;
          
          // 设置基本信息
          formState.id = detailData.id;
          formState.title = detailData.title;
          formState.categoryId = detailData.categoryId;
          formState.coverImage = detailData.coverImage;
          formState.description = detailData.description;
          formState.isActivity = detailData.isActivity || 0;
          formState.activityId = detailData.activityId;
          formState.activityName = detailData.activityName;
          imageUrl.value = detailData.coverImage;
          
          // 设置标签 - 确保标签数据正确处理
          if (detailData.tags) {
            // 如果标签是字符串，尝试解析为数组
            if (typeof detailData.tags === 'string') {
              try {
                formState.tags = JSON.parse(detailData.tags);
              } catch (e) {
                // 如果解析失败，尝试按逗号分隔
                formState.tags = detailData.tags.split(',').filter(tag => tag.trim() !== '');
              }
            } else if (Array.isArray(detailData.tags)) {
              formState.tags = detailData.tags;
            } else {
              formState.tags = [];
            }
          } else {
            formState.tags = [];
          }
          
          // 设置图片列表
          artworkImages.value = detailData.images || [];
          
          // 显示弹窗
          modalVisible.value = true;
        } else {
          message.error(response.data.message || '获取作品详情失败');
        }
      } catch (error) {
        console.error('获取作品详情失败:', error);
        message.error('获取作品详情失败');
      }
    };

    // 图片上传前检查
    const beforeUploadImage = (file) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('只能上传 JPG/PNG 格式的图片！');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片大小不能超过 2MB！');
      }
      return isJpgOrPng && isLt2M;
    };
    
    // 处理图片上传变化
    const handleImageChange = (info) => {
      if (info.file.status === 'uploading') {
        return;
      }
      if (info.file.status === 'done') {
        // 获取服务器返回的图片URL
        if (info.file.response.code === 200) {
          // 添加到图片列表
          const newImage = {
            id: Date.now(), // 临时ID
            artworkId: formState.id,
            imagePath: info.file.response.data,
            sort: artworkImages.value.length,
            isCover: artworkImages.value.length === 0 ? 1 : 0
          };
          artworkImages.value.push(newImage);
        } else {
          message.error('上传失败');
        }
      }
      if (info.file.status === 'error') {
        message.error('上传失败');
      }
    };
    
    // 移除图片
    const removeImage = (index) => {
      artworkImages.value.splice(index, 1);
      // 重新排序
      artworkImages.value.forEach((image, idx) => {
        image.sort = idx;
        if (idx === 0) {
          image.isCover = 1;
        } else {
          image.isCover = 0;
        }
      });
    };
    
    // 弹窗确认
    const handleModalOk = () => {
      // 如果选择了参加活动但没有选择具体活动，显示提示
      if (formState.isActivity === 1 && !formState.activityId) {
        message.warning('请选择一个活动');
        return;
      }
      
      formRef.value.validate().then(() => {
        modalLoading.value = true;
        const url = isEdit.value ? `/api/artwork/${formState.id}` : '/api/artwork';
        const method = isEdit.value ? 'put' : 'post';
        
        // 确保提交的数据正确
        const submitData = {...formState};
        // 如果不参加活动，清空活动相关字段
        if (submitData.isActivity === 0) {
          submitData.activityId = null;
          submitData.activityName = '';
        }
        
        // 添加图片数据
        submitData.images = artworkImages.value;
        
        axios[method](url, submitData)
          .then(response => {
            if (response.data.code === 200) {
              message.success(isEdit.value ? '编辑成功' : '新增成功');
              modalVisible.value = false;
              fetchArtworkList();
            } else {
              message.error(response.data.message || (isEdit.value ? '编辑失败' : '新增失败'));
            }
          })
          .catch(error => {
            console.error(isEdit.value ? '编辑失败:' : '新增失败:', error);
            message.error(isEdit.value ? '编辑失败' : '新增失败');
          })
          .finally(() => {
            modalLoading.value = false;
          });
      }).catch(error => {
        console.log('验证失败:', error);
      });
    };

    // 弹窗取消
    const handleModalCancel = () => {
      modalVisible.value = false;
    };

    // 删除作品
    const handleDelete = (id) => {
      axios.delete(`/api/artwork/${id}`)
        .then(response => {
          if (response.data.code === 200) {
            message.success('删除成功');
            fetchArtworkList();
          } else {
            message.error(response.data.message || '删除失败');
          }
        })
        .catch(error => {
          console.error('删除失败:', error);
          message.error('删除失败');
        });
    };

    // 审核弹窗相关
    const reviewModalVisible = ref(false);
    const reviewModalLoading = ref(false);
    const reviewFormRef = ref(null);
    const artworkImages = ref([]);
    const artworkDetail = ref({
      title: '',
      description: '',
      categoryName: '',
      viewCount: 0,
      favoriteCount: 0,
      commentCount: 0
    });
    
    // 图片预览相关
    const showImagePreview = ref(false);
    const previewImageUrl = ref('');
    const previewImageAlt = ref('图片预览');
    const currentImageIndex = ref(0);
    
    // 设置当前图片索引
    const setImage = (index) => {
      currentImageIndex.value = index;
    };
    
    /**
     * 预览图片
     * @param {string} imageUrl - 图片URL
     * @param {string} altText - 图片替代文本
     */
    const previewImage = (imageUrl, altText = '图片预览') => {
      previewImageUrl.value = imageUrl;
      previewImageAlt.value = altText;
      showImagePreview.value = true;
    };
    
    /**
     * 关闭图片预览
     */
    const closeImagePreview = () => {
      showImagePreview.value = false;
    };
    
    const reviewFormState = reactive({
      id: null,
      status: 2,
      rejectReason: '',
    });

    const reviewRules = {
      status: [
        { required: true, message: '请选择审核结果', trigger: 'change' }
      ],
      rejectReason: [
        { required: true, message: '请输入拒绝原因', trigger: 'blur', validator: (rule, value) => {
          if (reviewFormState.status === 3 && (!value || value.trim() === '')) {
            return Promise.reject('请输入拒绝原因');
          }
          return Promise.resolve();
        }}
      ],
    };

    // 显示审核弹窗
    const showReviewModal = async (record) => {
      reviewFormState.id = record.id;
      reviewFormState.status = 2;
      reviewFormState.rejectReason = '';
      
      // 获取作品详情
      try {
        const detailRes = await axios.get(`/api/artwork/${record.id}`);
        if (detailRes.data.code === 200) {
          artworkDetail.value = detailRes.data.data;
          
          // 数据加载完成后再显示弹窗
          reviewModalVisible.value = true;
        } else {
          message.error(detailRes.data.message || '获取作品详情失败');
        }
      } catch (error) {
        console.error('获取作品详情失败:', error);
        message.error('获取作品详情失败');
      }
    };

    // 审核弹窗确认
    const handleReviewModalOk = () => {
      reviewFormRef.value.validate().then(() => {
        reviewModalLoading.value = true;
        console.log(reviewFormState);
        axios.put(`/api/artwork/${reviewFormState.id}/review?status=${reviewFormState.status}&rejectReason=${reviewFormState.rejectReason}`)
          .then(response => {
            if (response.data.code === 200) {
              message.success('审核成功');
              reviewModalVisible.value = false;
              fetchArtworkList();
            } else {
              message.error(response.data.message || '审核失败');
            }
          })
          .catch(error => {
            console.error('审核失败:', error);
            message.error('审核失败');
          })
          .finally(() => {
            reviewModalLoading.value = false;
          });
      }).catch(error => {
        console.log('验证失败:', error);
      });
    };

    // 审核弹窗取消
    const handleReviewModalCancel = () => {
      reviewModalVisible.value = false;
    };

    onMounted(() => {
      fetchArtworkList();
      fetchCategoryList();
    });

    return {
      tableLoading,
      artworkList,
      categoryList,
      pagination,
      searchForm,
      columns,
      fetchArtworkList,
      handleTableChange,
      handleSearch,
      resetSearch,
      getStatusText,
      getStatusColor,
      modalVisible,
      modalTitle,
      modalLoading,
      formRef,
      formState,
      rules,
      showAddModal,
      showEditModal,
      handleModalOk,
      handleModalCancel,
      handleDelete,
      reviewModalVisible,
      reviewModalLoading,
      reviewFormRef,
      reviewFormState,
      reviewRules,
      showReviewModal,
      handleReviewModalOk,
      handleReviewModalCancel,
      imageUrl,
      imageLoading,
      fileList,
      beforeUpload,
      handleChange,
      artworkDetail,
      // 图片预览相关
      showImagePreview,
      previewImageUrl,
      previewImageAlt,
      previewImage,
      closeImagePreview,
      currentImageIndex,
      setImage,
      // 活动选择相关
      activityModalVisible,
      activityList,
      activityLoading,
      activitySearchKeyword,
      activityPagination,
      activityColumns,
      showActivityModal,
      handleActivityModalCancel,
      selectActivity,
      getActivityStatusText,
      getActivityStatusColor,
      handleActivityTableChange,
      searchActivities,
      artworkImages,
      beforeUploadImage,
      handleImageChange,
      removeImage
    };
  }
});
</script>

<style scoped>
.artwork-list {
  padding: 24px;
}

.search-card {
  margin-bottom: 24px;
}

.artwork-detail {
  padding: 16px;
}

.artwork-detail h3 {
  margin-bottom: 16px;
  color: #1890ff;
}

.description {
  margin-bottom: 24px;
  color: #666;
}

.artwork-images {
  margin: 20px 0;
  width: 100%;
  height: 300px;
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.carousel-slide {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #4b4b4b;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.review-form {
  margin-top: 24px;
}

.reject-reason {
  margin-top: 16px;
}

.activity-tip {
  margin-top: 8px;
}

.tag-tips {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  line-height: 1.5;
}

.ant-input-group-wrapper {
  width: 100%;
}

.artwork-info {
  background-color: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  
  p {
    margin-bottom: 8px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    strong {
      color: #666;
      margin-right: 8px;
    }
  }
}

.tree-node-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.node-title {
  display: flex;
  align-items: center;
}

.node-icon {
  margin-right: 8px;
}

.node-tag {
  margin-left: 8px;
}

/* 作品图片上传和预览样式 */
.artwork-images-container {
  width: 100%;
}

.artwork-images-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
}

.image-item {
  position: relative;
  width: 104px;
  height: 104px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #d9d9d9;
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
}

.image-actions {
  position: absolute;
  top: 5px;
  right: 5px;
  display: flex;
  gap: 5px;
}

.image-actions .ant-btn {
  width: 24px;
  height: 24px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.slick-arrow.custom-slick-arrow) {
  width: 45px;
  height: 45px;
  font-size: 25px;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.8);
  border-radius: 50%;
  transition: ease all 0.3s;
  opacity: 0.6;
  text-align: center;
  padding: 10px;
  z-index: 1;
}
:deep(.slick-arrow.custom-slick-arrow:before) {
  display: none;
}
:deep(.slick-arrow.custom-slick-arrow:hover) {
  color: #fff;
  opacity: 0.8;
}
</style>